package elevation.general;

import java.io.IOException;
import java.net.MalformedURLException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import elevation.general.utils.DialogError;
import elevation.general.utils.Facebook;
import elevation.general.utils.Facebook.DialogListener;
import elevation.general.utils.FacebookError;

public class ShareUtils {

	private static ShareUtils _instance;

	private static final String FACEBOOK_APP_ID = "155006591286895";

	private static final String[] FACEBOOK_PERMS = new String[] { "publish_stream", "read_stream", "offline_access" };

	private final static String PREFIX_FACEBOOK = "facebook_preference_";

	private ElevationActivity mActivity;
	private String mShareText;
	private static Facebook mFacebook;

	private ShareUtils() {
	}

	public static ShareUtils getInstance() {
		if (_instance == null) {
			_instance = new ShareUtils();
		}
		return _instance;
	}

	public boolean shareFacebook(final ElevationActivity activity, String shareText) {

		mActivity = activity;
		mShareText = shareText;
		if (mFacebook == null)
			mFacebook = new Facebook(FACEBOOK_APP_ID);

		String token = readFacebookToken();
		if (token != null) {
			updateStatus(token);
		} else {
			mActivity.hideProgressAsync();

			mFacebook.authorize(activity, FACEBOOK_PERMS, Facebook.FORCE_DIALOG_AUTH, new DialogListener() {

				public void onFacebookError(FacebookError e) {
					errorFacebook();
				}

				public void onError(DialogError e) {
					errorFacebook();
				}

				public void onComplete(Bundle values) {
					String token = values.getString(Facebook.TOKEN);
					configFacebookToken(token);
					updateStatus(token);
				}

				public void onCancel() {
					errorFacebook();
				}

				public void errorFacebook() {
					mActivity.hideProgressAsync();

					AlertDialog.Builder builder;
					builder = new AlertDialog.Builder(mActivity);
					builder.setTitle(R.string.warning).setIcon(android.R.drawable.ic_dialog_alert)
							.setMessage(mActivity.getString(R.string.facebook_share_error))
							.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog, int which) {
								}

							}).create().show();
				}
			});
		}
		return true;
	}

	private void updateStatus(String accessToken) {
		try {
			Bundle bundle = new Bundle();

			bundle.putString("message", mShareText);
			bundle.putString("name", mActivity.getString(R.string.app_name));
			bundle.putString("link", "https://market.android.com/details?id=elevation.general");
			bundle.putString("caption", " ");
			bundle.putString("picture",
					"https://lh5.ggpht.com/dNiXjWZbNtBdddXYYBew0qT0XHfqdiNUFxFGCErPV8hHIcHdQ8ezgUQ3u1Bf3lpLdeM=w78-h78");

			bundle.putString(Facebook.TOKEN, accessToken);

			mFacebook.request("me/feed", bundle, "POST");

			mActivity.hideProgressAsync();
			AlertDialog.Builder builder;
			builder = new AlertDialog.Builder(mActivity);
			builder.setTitle(R.string.info_label).setIcon(android.R.drawable.ic_dialog_info)
					.setMessage(mActivity.getString(R.string.facebook_share_ok))
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
						}

					}).create().show();

		} catch (MalformedURLException e) {
			// e.printStackTrace();
		} catch (IOException e) {
			// e.printStackTrace();
		}
	}

	private void configFacebookToken(String token) {
		SharedPreferences preferences;
		preferences = mActivity.getApplicationContext().getSharedPreferences(PREFIX_FACEBOOK, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();

		editor.putString("share_fb", token);
		editor.commit();
	}

	private String readFacebookToken() {
		SharedPreferences preferences;
		preferences = mActivity.getApplicationContext().getSharedPreferences(PREFIX_FACEBOOK, Context.MODE_PRIVATE);

		String token = preferences.getString("share_fb", null);

		if (token != null) {
			try {
				return token;
			} catch (Exception e) {
				return null;
			}
		}
		return null;
	}

	public void resetFacebook(final Context context) {

		Thread t = new Thread() {
			@Override
			public void run() {
				if (mFacebook != null) {
					try {
						mFacebook.logout(context);
					} catch (MalformedURLException e) {
						// e.printStackTrace();
					} catch (IOException e) {
						// e.printStackTrace();
					}
				}
			}
		};
		t.start();
	}
}
